package org.example.xx2.controller;

import org.example.xx2.dto.ApiResponse;
import org.example.xx2.model.User;
import org.example.xx2.service.UserService;
import org.example.xx2.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/admin")
@CrossOrigin(origins = "*")
public class AdminController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 获取所有用户列表
     */
    @GetMapping("/users")
    public ApiResponse<List<User>> getUsers(HttpServletRequest httpRequest,
                                           @RequestParam(required = false) Integer page,
                                           @RequestParam(required = false) Integer size) {
        if (!isAdmin(httpRequest)) {
            return ApiResponse.error(403, "权限不足");
        }

        // 如果提供了分页参数，则使用分页查询
        if (page != null && size != null) {
            return userService.getUsersByPage(page, size);
        }

        // 否则返回所有用户
        return userService.getAllUsers();
    }

    /**
     * 更新用户信息（管理员）
     */
    @PutMapping("/users/{userId}")
    public ApiResponse<String> updateUserByAdmin(HttpServletRequest httpRequest,
                                               @PathVariable Integer userId,
                                               @Valid @RequestBody User user) {
        if (!isAdmin(httpRequest)) {
            return ApiResponse.error(403, "权限不足");
        }
        return userService.updateUserByAdmin(userId, user);
    }

    /**
     * 删除用户
     */
    @DeleteMapping("/users/{userId}")
    public ApiResponse<String> deleteUser(HttpServletRequest httpRequest,
                                        @PathVariable Integer userId) {
        if (!isAdmin(httpRequest)) {
            return ApiResponse.error(403, "权限不足");
        }
        return userService.deleteUser(userId);
    }

    /**
     * 检查是否为管理员
     */
    private boolean isAdmin(HttpServletRequest httpRequest) {
        String token = getTokenFromHeader(httpRequest);
        if (token == null) return false;

        String role = jwtUtil.getRoleFromToken(token);
//        log.info("Checking admin access for role: {}", role); // 添加日志

        // 同时支持数字和字符串形式的角色标识
        return "2".equals(role) || "ADMIN".equalsIgnoreCase(role);
    }
    private String getTokenFromHeader(HttpServletRequest request) {
        String header = request.getHeader("Authorization");
        if (header != null && header.startsWith("Bearer ")) {
            return header.substring(7);
        }
        return null;
    }
} 